var express = require('express');
var svgCaptcha = require('svg-captcha');
var router = express.Router();
var {
  employeeModel,
  roleModel,
  departmentModel,
  permissionModel,
  loginModel,
} = require('../../../model/model');
/* GET home page. */

router.get('/', async (req, res) => {
  res.send({
    code: 200,
  });
});

//添加后台员工信息
router.post('/addemployee', async (req, res) => {
  console.log(req.body);
  employeeModel.create(req.body);
  res.send({
    code: 200,
    msg: '添加成功',
  });
});

//添加角色表
router.post('/addrole', async (req, res) => {
  console.log(req.body);
  await roleModel.create(req.body);
  res.send({
    code: 200,
    msg: '添加成功',
  });
});

//添加部门表
router.post('/adddepartment', async (req, res) => {
  console.log(req.body);
  departmentModel.create(req.body);
  res.send({
    code: 200,
    msg: '添加成功',
  });
});

//添加权限表
router.post('/addpermission', async (req, res) => {
  console.log(req.body);
  await permissionModel.create(req.body);
  res.send({
    code: 200,
    msg: '添加成功',
  });
});

router.get('/getemployee_content', async (req, res) => {
  console.log(req.query);
  //获取符合参数的人员表_id
  let user = await employeeModel.find(req.query);
  console.log(user);
  let user_id = user[0]._id;
  let userlist = await employeeModel
    .find({ _id: user_id })
    .populate('role')
    .populate('department');
  // 给一个列表在这个数据库中查询

  let a = userlist[0].role.map((item) => {
    return item.name;
  });
  let permission = await permissionModel.find({ name: a }).populate('children');
  res.send({
    userlist,
    permission,
  });
});

router.post('/getsvgCaptcha', async (req, res) => {
  var captcha = svgCaptcha.create({
    size: 4, // 验证码长度
    width: 100, // 验证码图片宽度
    height: 35,
    fontSize: 40,
    noise: 2, // 干扰线条的数量
    color: true,
  });

  res.send({
    data: captcha.data,
    text: captcha.text,
    code: 200,
  });
});

// 手机短信验证码
const UniSMS = require('unisms').default;
const iponecode = '';
router.post('/getphonecode', async (req, res) => {
  const client = new UniSMS({
    accessKeyId: 'jtSDCWuXQMDMruxAEH2HKjU2Y9DfYSpDQroYF6J3entHbDXtj',
    accessKeySecret: 'P9Yn7Mda4rqYM5CYs2u3RnmucgPsBz', // 若使用简易验签模式请删除此行
  });

  //生成随机四位数验证码
  var code = Math.floor(Math.random() * 9000) + 1000;
  // 发送短信
  client
    .send({
      to: JSON.stringify(req.body.tell),
      signature: '王梦菡',
      templateId: 'pub_verif_login',
      templateData: {
        code: code,
      },
    })
    .then((ret) => {
      // console.info('Result:', ret);
      iponecode = code;
      res.send({
        code: 200,
        msg: '发送成功',
      });
    })
    .catch((e) => {
      console.error(e);
    });
});


router.post('/addLogin',(req,res)=>{
  console.log(req.body)
  loginModel.create(req.body)
  res.send({
    code:200,
    msg:'登录成功'
  })
})

module.exports = router;
